package boun.center;

import java.io.IOException;
import java.util.Calendar;
import java.util.Collections;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Scroller;

public class CalendarActivity extends Activity {
	ListView lv;
	CalendarAdapter ca;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calendar_list);
		lv = (ListView) findViewById(R.id.list);
		ca = (CalendarAdapter) getLastNonConfigurationInstance();
		if(ca == null){
			new FetchingTask().execute();
		}
		else {
			lv.setAdapter(ca);
		}
		
	}
	
	@Override
	public Object onRetainNonConfigurationInstance(){
		return ca;
	}
	
	private void scrollToCurrentDate() {
		int index = getClosestDateIndex();
		View v = lv.getChildAt(0);
		int top = (v == null) ? 0: v.getTop();
		lv.setSelectionFromTop(index, top);
	}
	private int getClosestDateIndex() {
		Calendar now = Calendar.getInstance();
		int index = 0;
		for(;index<lv.getCount();index++){
			if(now.compareTo(((CalendarEvent)lv.getItemAtPosition(index)).getBeginDate()) == -1)break;
		}
		return index;
	}

	
	class FetchingTask extends AsyncTask<Void,Void,CalendarAdapter>{
		ProgressDialog dialog;
		public FetchingTask(){
			dialog = new ProgressDialog(CalendarActivity.this);
		}
		@Override
		protected CalendarAdapter doInBackground(Void... params) {
			
			try {
				ca = new CalendarAdapter(CalendarActivity.this);
				return ca;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPreExecute(){
			dialog = ProgressDialog.show(CalendarActivity.this,"","Loading..",true);
		}
		@Override
		protected void onPostExecute(CalendarAdapter la){
			dialog.dismiss();
			lv.setAdapter(la);
			scrollToCurrentDate();
		}
	}
}
